/*
 * Copyright (C) 2018 Sergej Shafarenka, www.halfbit.de
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package magnet.processor.registry;

import magnet.Registry;
import magnet.processor.MagnetProcessorEnv;

import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import java.util.ArrayList;
import java.util.Set;

public class RegistryProcessor {

    public static final String REGISTRY_CLASS_NAME = "magnet.internal.MagnetIndexer";
    public static final String INDEX_PACKAGE = "magnet.index";

    private MagnetProcessorEnv env;
    private RegistryParser registryParser;
    private RegistryGenerator magnetIndexerGenerator;
    private boolean generateRegistryOnNextRound = false;

    public RegistryProcessor(MagnetProcessorEnv env) {
        this.env = env;
        registryParser = new RegistryParser(env.getAnnoation());
        magnetIndexerGenerator = new RegistryGenerator();
    }

    public boolean process(RoundEnvironment roundEnv) {

        TypeElement generatedRegistryElement = env.getElements().getTypeElement(REGISTRY_CLASS_NAME);
        if (generatedRegistryElement != null) {
            return false;
        }

        Set<? extends Element> annotatedRegistryElement = roundEnv.getElementsAnnotatedWith(Registry.class);
        if (!generateRegistryOnNextRound) {
            generateRegistryOnNextRound = !annotatedRegistryElement.isEmpty();
            return false;
        }

        PackageElement packageElement = env.getElements().getPackageElement(INDEX_PACKAGE);
        Model.Registry registry;

        if (packageElement != null) {
            registry = registryParser.parse(packageElement);
        } else {
            registry = new Model.Registry(new ArrayList<Model.InstanceFactory>());
        }

        magnetIndexerGenerator
                .generate(registry)
                .writeInto(env.getFiler());

        return true;
    }
}
